package com.mlnx.netty.maibb.handler;

import com.mlnx.common.utils.MyLog;
import com.mlnx.netty.base.message.BpMessage;
import com.mlnx.netty.maibb.pojo.MemoryData;
import com.mlnx.netty.maibb.pojo.SingleData;
import com.mlnx.netty.maibb.uitl.KangtaiBpPacket;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * Created by amanda.shan on 2019/11/26.
 */
public class MaibbServerHandle extends ByteToMessageDecoder {
    private MyLog log = MyLog.getLog(getClass());

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        // 可读的数据长度
        int len = in.readableBytes();
        byte[] buffer = new byte[len];
        in.readBytes(buffer);
        SingleData singleData = KangtaiBpPacket.checkCode(buffer);
        if (singleData != null) {//响应
            ctx.writeAndFlush(Unpooled.copiedBuffer(singleData.getCode()));
            if(buffer[7] == 3) {//单次数据
                BpMessage bpMessage =new BpMessage();
                bpMessage.setDbp(singleData.getDbp());
                bpMessage.setHeart(singleData.getPulse());
                bpMessage.setSbp(singleData.getSbp());
                bpMessage.setDeviceId(singleData.getDeviceId());
                log.info("收到数据：sbp{}device:{}",singleData.getSbp(),singleData.getDeviceId());
                ctx.fireChannelRead(bpMessage);
            }else if(buffer[7] == 4){//记忆数据
                List<MemoryData> memoryData = singleData.getMemoryData();
                for(MemoryData md:memoryData){
                    BpMessage bpMessage =new BpMessage();
                    bpMessage.setDbp(md.getDbp());
                    bpMessage.setHeart( md.getPulse());
                    bpMessage.setSbp(md.getSbp());
                    bpMessage.setDeviceId(md.getDeviceId());
//                    md.getSbp();
//                    md.getDbp();
//                    md.getPulse();
                    ctx.fireChannelRead(bpMessage);
                    log.info("收到数据：sbp{}",md.getDeviceId());
                }
            }
        }
        in.clear();

    }
}
